package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/utils"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// Response 统一响应结构
type Response struct {
	Success bool        `json:"success"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
	Code    int         `json:"code,omitempty"`
}

// PaginationData 分页数据结构
type PaginationData struct {
	List      interface{} `json:"list"`
	Total     int64       `json:"total"`
	Page      int         `json:"page"`
	PageSize  int         `json:"page_size"`
	TotalPage int         `json:"total_page"`
}

// BaseController 基础控制器，提供通用方法
type BaseController struct {
	web.Controller
}

// Success 返回成功响应
func (c *BaseController) Success(message string, data interface{}) {
	c.Data["json"] = Response{
		Success: true,
		Message: message,
		Data:    data,
	}
	c.ServeJSON()
}

// SuccessWithPagination 返回分页成功响应
func (c *BaseController) SuccessWithPagination(message string, list interface{}, total int64, page, pageSize int) {
	c.Data["json"] = Response{
		Success: true,
		Message: message,
		Data: map[string]interface{}{
			"list":       list,
			"total":      total,
			"page":       page,
			"page_size":  pageSize,
			"total_page": utils.GetTotalPage(total, pageSize),
		},
	}
	c.ServeJSON()
}

// Fail 返回失败响应
func (c *BaseController) Fail(message string) {
	c.Data["json"] = Response{
		Success: false,
		Message: message,
	}
	c.ServeJSON()
}

// FailWithCode 返回带错误码的失败响应
func (c *BaseController) FailWithCode(message string, code int) {
	c.Data["json"] = Response{
		Success: false,
		Message: message,
		Code:    code,
	}
	c.ServeJSON()
}

// GetAdmin 获取当前登录管理员
func (c *BaseController) GetAdmin() (*models.Admin, bool) {
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Fail("没有操作权限")
		return nil, false
	}
	return admin, true
}

// LogOperation 记录操作日志
func (c *BaseController) LogOperation(admin *models.Admin, operationType, description string) {
	logEntry := &models.OperationLog{
		UserId:        admin.Id,
		Username:      admin.Username,
		Method:        c.Ctx.Request.Method,
		Path:          c.Ctx.Request.URL.Path,
		Ip:            c.Ctx.Input.IP(),
		OperationType: operationType,
		Description:   description,
	}
	if err := models.AddOperationLog(logEntry); err != nil {
		logs.Error("记录操作日志失败: %v", err)
	}
}

// ValidateIDParam 验证ID参数
func (c *BaseController) ValidateIDParam() (int64, bool) {
	idStr := c.Ctx.Input.Param(":id")
	id, err := utils.ParseInt64(idStr)
	if err != nil {
		c.Fail("无效的ID参数")
		return 0, false
	}
	return id, true
}

// GetPaginationParams 获取分页参数
func (c *BaseController) GetPaginationParams() (int, int) {
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return page, pageSize
}

// ErrorResponse 返回错误响应（兼容旧代码）
func ErrorResponse(message string) map[string]interface{} {
	return map[string]interface{}{
		"success": false,
		"message": message,
	}
}

// SuccessResponse 返回成功响应（兼容旧代码）
func SuccessResponse(data interface{}) map[string]interface{} {
	return map[string]interface{}{
		"success": true,
		"message": "操作成功",
		"data":    data,
	}
}

// FailureResponse 返回失败响应（兼容旧代码）
func FailureResponse(err error) map[string]interface{} {
	return map[string]interface{}{
		"success": false,
		"message": err.Error(),
	}
}
